<template>
    <div class="video-uploader">
        <el-upload class="upload-demo" ref="uploadRef" :auto-upload="true" :before-upload="beforeUpload" :show-file-list="false" accept="video/mp4">
            <el-button color="#f06423">{{ $t('course.resource_edit.add_dialog.label_4_btn') }}</el-button>
            <div slot="tip" class="el-upload__tip">{{ $t('course.resource_edit.add_dialog.label_11_placeholder') }}</div>
        </el-upload>

        <!-- 上传进度 -->
        <!-- <el-progress v-if="uploading && progress > 0" :percentage="progress" :format="formatProgress" status="success"></el-progress> -->
        <div class="progress-wrap" v-if="selectedFile && selectedFile.name">
            <div class="progress-content">
                <el-progress :percentage="progress" :stroke-width="22" :text-inside="true" status="success"></el-progress>
                <p v-if="selectedFile">{{ formatFileSize(selectedFile.size) }}</p>
            </div>
            <div class="file-name">
                <el-icon size="16" color="#4c4c4c"><VideoPlay /></el-icon>
                <span>{{ selectedFile.name || '--' }}</span>
                <el-button v-if="selectedFile && !isSuccess" color="#00A9CE" :loading="uploading" @click="startUpload" :disabled="uploading">
                    {{ uploading ? '上載中...' : '開始上載' }}
                </el-button>
                <el-button v-if="uploading && !isSuccess" color="#435764" @click="cancelUpload"> 取消上載 </el-button>
            </div>
        </div>
        <p v-else-if="videoUrl || props.videoUrl" class="file-name">
            <el-icon size="16" color="#4c4c4c"><VideoPlay /></el-icon>
            <span v-if="videoUrl">{{ videoUrl.split('/').pop() }}</span>
            <span v-else-if="props.videoUrl">{{ props.videoUrl.split('/').pop() }}</span>
        </p>
        <!-- <div v-if="uploadLogs.length" class="upload-logs" style="display: none">
            <h4>上传日志：</h4>
            <ul>
                <li v-for="(log, index) in uploadLogs" :key="index">{{ log }}</li>
            </ul>
        </div> -->
    </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

import { ElMessage } from 'element-plus'

import uploadChunkService from '@/api/uploadChunk'

const props = defineProps<{
    videoId: number
    videoUrl: string
    panopto_video_id: number
}>()
const emit = defineEmits<{
    relVideUrl: [{ url: string; panopto_video_id: number }]
}>()

const videoUrl = ref<string>('')
const panoptoVideoId = ref<number>(props.panopto_video_id)

// 選擇文件
const selectedFile = ref<File | null>(null)
const beforeUpload = (file: any) => {
    // 限制文件类型
    if (!file.type.includes('video/mp4')) {
        ElMessage.error('请上传 MP4 格式视频')
        return false
    }

    // 记录选中的文件
    selectedFile.value = file
    return false // 阻止默认上传
}

// 進度條
const progress = ref<number>(0)
const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'

    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 开始上传
const isSuccess = ref<boolean>(false) //是否上传成功
const uploading = ref<boolean>(false) //是否上传中
const startUpload = () => {
    if (!selectedFile.value || uploading.value) return

    uploadChunkService.checkAuth().then(res => {
        if (res.authorized) {
            uploadVideo()
        } else {
            window.open(res.authorization_url, '_blank')
        }
    })
}
const cancelUpload = () => {
    props.videoId
}
function uploadVideo() {
    if (!selectedFile.value) return

    uploading.value = true
    const formData = new FormData()
    const file = selectedFile.value
    formData.append('file', file)
    formData.append('panopto_video_id', panoptoVideoId.value.toString())
    uploadChunkService
        .uploadVideo(formData)
        .then(res => {
            panoptoVideoId.value = res.panopto_video_id
            pollUploadProgress()
        })
        .catch(() => {
            uploading.value = false
            ElMessage.error('上載失敗')
        })
}
// 輪詢上傳進度
function pollUploadProgress() {
    const interval = setInterval(() => {
        uploadChunkService
            .getVideoStatus(panoptoVideoId.value)
            .then(res => {
                switch (res.State) {
                    case 0:
                        clearInterval(interval)
                        uploading.value = false
                        break
                    case -1:
                        clearInterval(interval)
                        uploading.value = false
                        break
                    case 2:
                        clearInterval(interval)
                        ElMessage.warning('用戶取消上載')
                        uploading.value = false
                        break
                    case 1:
                        progress.value = 50
                        break
                    case 3:
                        progress.value = 90
                        break
                    case 4:
                        isSuccess.value = true
                        progress.value = 100
                        uploading.value = false
                        clearInterval(interval)
                        videoUrl.value = res.PlayUrl
                        emit('relVideUrl', { url: videoUrl.value, panopto_video_id: panoptoVideoId.value })
                        break
                    default:
                        clearInterval(interval)
                        ElMessage.error('上載失敗')
                        uploading.value = false
                        break
                }
            })
            .catch(err => {
                clearInterval(interval)
                ElMessage.error('上載失敗')
                uploading.value = false
            })
    }, 5000)
}
</script>

<style lang="less" scoped>
.upload-demo {
    margin-bottom: 10px;
}

.upload-logs {
    margin-top: 16px;
    max-height: 200px;
    overflow-y: auto;
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
}

.upload-logs h4 {
    margin-top: 0;
    margin-bottom: 8px;
    font-size: 14px;
}

.upload-logs ul {
    list-style: none;
    padding: 0;
    margin: 0;
    font-size: 12px;
}

.upload-logs li {
    margin-bottom: 4px;
    color: #606266;
}
// .video-uploader{
//     width: 100%
// }
.progress-wrap {
    .progress-content {
        width: 100%;
        margin-bottom: 10px;
        display: grid;
        grid-template-columns: 1fr 100px;
        gap: 10px;
    }
}
.el-upload__tip {
    margin-left: 10px;
}
.file-name {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    span {
        margin-left: 5px;
        margin-right: 10px;
        line-height: 1.2;
    }
}
</style>
